package com.glorysoft.lipuxinpda.activity

import android.Manifest
import android.content.pm.PackageManager
import android.provider.Settings
import android.telephony.TelephonyManager
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.glorysoft.lipuxinpda.R
import com.glorysoft.lipuxinpda.base.App
import com.glorysoft.lipuxinpda.base.BaseActivity
import com.glorysoft.lipuxinpda.base.Constant.FILE_URL
import com.glorysoft.lipuxinpda.base.Constant.NET_URL
import com.glorysoft.lipuxinpda.base.Constant.loginEntity
import com.glorysoft.lipuxinpda.entity.BaseEntity
import com.glorysoft.lipuxinpda.entity.LoginEntity
import com.glorysoft.lipuxinpda.utils.MyUtils.isFastClick
import com.glorysoft.lipuxinpda.utils.NetUtils
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils
import kotlinx.android.synthetic.main.activity_login.*
import java.util.*

/**
 * FileName: LoginActivity
 * Author: XJH
 * Date: 2021/4/8 14:57
 * Description:
 * History:
 */
class LoginActivity : BaseActivity(), View.OnClickListener {
    override fun getLayoutResId(): Int {
        return R.layout.activity_login
    }

    override fun initView() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        val arrayOf = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE)
        var list = listOf<String>()
        for (i in arrayOf.indices) {
            if (ActivityCompat.checkSelfPermission(this, arrayOf[i])
                    !== PackageManager.PERMISSION_GRANTED)
                list += arrayOf[i]
        }

        if (list.size > 0) {
            ActivityCompat.requestPermissions(this, list.toTypedArray(), 0)
        } else {
            Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show()
        }

//        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                !== PackageManager.PERMISSION_GRANTED) {
//            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
//            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show()
//            }
//            var arrayOf = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//            //申请权限
//            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
//        } else {
//            Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show()
//        }


        ivSetting.setOnClickListener(this)
        btnLogin.setOnClickListener(this)
    }

    override fun initData() {
        //删除日志
        FreeApi_Utils.deleteLog()
        NET_URL = FreeApi_SharePreferencesUtils.getSharePre("URL_FILE", "URL_IP", NET_URL, App.app)
        FILE_URL = FreeApi_SharePreferencesUtils.getSharePre("URL_FILE", "FILE_IP", FILE_URL, App.app)
    }

    override fun getBaseEntity(): FreeUI_AddViewEntity? {
        return null
    }

    override fun onClick(p0: View?) {
        if (isFastClick) {
            showToast("您点击的太快了", false)
            return
        }

        when (p0?.id) {
            R.id.ivSetting -> FreeApi_Utils.skipWithExtraIntent(
                    //请输入密码
                    "header",
                    this@LoginActivity,
                    SettingActivity::class.java
            )
            R.id.btnLogin -> {
                var workNo = ""
                if (etMobile!!.text.toString().trim { it <= ' ' }.isEmpty()) {
                    workNo = etMobile!!.text.toString().trim { it <= ' ' }
                    showToast("请输入用户名", false)
                    return
                }
                if (etPassword!!.text.toString().trim { it <= ' ' }.isEmpty()) {
                    showToast("请输入密码", false)
                    return
                }

                //region 测试
//                showToast("登录成功", true)
//                loginEntity.worK_NO = workNo
//                FreeApi_Utils.skipWithExtraIntent("", this@LoginActivity, HomeActivity::class.java)
//                finish()

                //endregion
                requestLogin()

            }
        }
    }

    private fun requestLogin() {
        val callBack: FreeUI_EntityCallBack<BaseEntity<LoginEntity>> = object : FreeUI_DialogEntityCallBack<BaseEntity<LoginEntity>>(object : TypeToken<BaseEntity<LoginEntity>>() {}.type, supportFragmentManager, this) {
            override fun onSuccess
                    (response: Response<BaseEntity<LoginEntity>>) {
                if (response.body().isSuccess(supportFragmentManager)) {
                    showToast("登录成功", true)
                    loginEntity = response.body().data.body
                    loginEntity.worK_NO = etMobile!!.text.toString().trim { it <= ' ' }
                    FreeApi_Utils.skipWithExtraIntent("", this@LoginActivity, HomeActivity::class.java)
                    finish()
                }
            }

            override fun onError(response: Response<BaseEntity<LoginEntity>>) {
                super.onError(response)
                loadError(response.exception, "PDALogin")
            }
        }

        val map: MutableMap<String, String> = HashMap()
        map["WORK_NO"] = etMobile!!.text.toString().trim { it <= ' ' }
        map["PASSWORD"] = etPassword!!.text.toString().trim { it <= ' ' }
        NetUtils().requestPostNet("$NET_URL/PDALoginRequest", this, map, callBack)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val telephonyManager = this.getSystemService(TELEPHONY_SERVICE) as TelephonyManager
        App.IMEI_ID = telephonyManager.deviceId
        if (App.IMEI_ID == null) {
            App.IMEI_ID = Settings.Secure.getString(applicationContext.contentResolver, Settings.Secure.ANDROID_ID)
        }

    }
}